package com.itcast.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itcast.constant.MessageConstant;
import com.itcast.constant.RedisMessageConstant;
import com.itcast.entity.Result;
import com.itcast.pojo.Order;
import com.itcast.service.OrderService;
import com.itcast.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 预约体检提交
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //判断验证码是否正确
        //获取手机号
        String telephone = (String) map.get("telephone");
        //获取redis中的验证码
        String param = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //获取前台传递的验证码
        String validateCode = (String) map.get("validateCode");
        if (telephone!=null && param!=null && param.equals(validateCode)){
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约类型，微信预约、电话预约
            Result result = null;
            try {
                //验证码正确,调用服务
                result = orderService.submit(map);
            }catch (Exception e){
                e.printStackTrace();
                return result;
            }
            //预约成功，发送预约成功提示信息
            /*if (result.isFlag()){
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }*/
            System.out.println("预约成功");
            return result;
        }else {
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //根据id查询数据
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
